



import json
import requests
from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods

# DeepSeek API配置 - 请替换为您的实际API Key
DEEPSEEK_API_KEY = ""  # 在此处填写您的DeepSeek API Key
DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions"


@csrf_exempt
@require_http_methods(["POST"])
def chat_with_ai(request):
    """
    处理AI聊天请求的视图函数 - 使用DeepSeek API
    """
    try:
        # 解析请求数据
        data = json.loads(request.body)
        user_message = data.get('message', '')

        if not user_message:
            return JsonResponse({'error': '消息不能为空'}, status=400)

        # 准备API请求头和数据
        headers = {
            'Content-Type': 'application/json',
            'Authorization': f'Bearer {DEEPSEEK_API_KEY}'
        }

        payload = {
            'model': 'deepseek-chat',  # DeepSeek聊天模型
            'messages': [
                {'role': 'system', 'content': '你是一个有用、准确、简洁的AI助手。'},
                {'role': 'user', 'content': user_message}
            ],
            'max_tokens': 2048,
            'temperature': 0.7,
            'stream': False
        }

        # 发送请求到DeepSeek API
        try:
            response = requests.post(DEEPSEEK_API_URL, headers=headers, json=payload, timeout=30)
            response_data = response.json()

            # 检查API响应
            if response.status_code == 200:
                ai_message = response_data['choices'][0]['message']['content']
                return JsonResponse({'message': ai_message})
            else:
                error_msg = response_data.get('error', {}).get('message', '未知错误')
                return JsonResponse({'error': f'API错误: {error_msg}'}, status=500)

        except requests.exceptions.Timeout:
            return JsonResponse({'error': '请求超时，请稍后重试'}, status=500)
        except requests.exceptions.RequestException as e:
            return JsonResponse({'error': f'网络错误: {str(e)}'}, status=500)

    except json.JSONDecodeError:
        return JsonResponse({'error': '无效的JSON数据'}, status=400)
    except Exception as e:
        return JsonResponse({'error': f'服务器错误: {str(e)}'}, status=500)


def chat_page(request):
    """
    渲染聊天页面的视图函数
    """
    return render(request, 'chat.html')


# 可选：添加一个简单的测试路由
@csrf_exempt
def test_api_connection(request):
    """
    测试API连接状态的视图
    """
    try:
        headers = {
            'Content-Type': 'application/json',
            'Authorization': f'Bearer {DEEPSEEK_API_KEY}'
        }

        payload = {
            'model': 'deepseek-chat',
            'messages': [{'role': 'user', 'content': '你好，请回复"连接成功"'}],
            'max_tokens': 10
        }

        response = requests.post(DEEPSEEK_API_URL, headers=headers, json=payload, timeout=10)

        if response.status_code == 200:
            return JsonResponse({'status': 'success', 'message': 'API连接正常'})
        else:
            return JsonResponse({'status': 'error', 'message': f'API连接失败: {response.status_code}'})

    except Exception as e:
        return JsonResponse({'status': 'error', 'message': f'连接测试失败: {str(e)}'})
